<template>
  <div class="page-container">
    <el-card class="card-container">
      <template #header>
        <div class="card-header">
          <span>相册管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增相册
          </el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="相册名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入相册名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-container">
        <el-button
          type="danger"
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="相册名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
                 <el-table-column label="封面" width="120">
           <template #default="{ row }">
             <el-image
               v-if="row.coverUrl"
               :src="getCoverUrl(row.coverUrl)"
               :preview-src-list="[getCoverUrl(row.coverUrl)]"
               fit="cover"
               style="width: 60px; height: 60px; border-radius: 4px;"
               @error="handleImageError"
             />
             <el-empty v-else description="无封面" :image-size="40" />
           </template>
         </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="相册名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入相册名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入相册描述"
          />
        </el-form-item>
                 <el-form-item label="封面URL" prop="coverUrl">
           <el-input 
             v-model="form.coverUrl" 
             placeholder="请输入任意图片URL，支持百度、小红书等平台的图片" 
           />
                       <div class="form-tip">
              <div style="margin-bottom: 8px; font-size: 12px; color: #909399;">
                💡 提示：支持输入任意图片URL或上传本地图片。系统会自动去重，相同图片不会重复保存。百度、小红书等平台的图片会自动通过代理访问。
              </div>
              <div class="upload-actions">
                <el-upload
                  v-if="uploadEnabled"
                  ref="uploadRef"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :http-request="handleUpload"
                  accept="image/*"
                  class="upload-btn"
                >
                  <el-button type="text" size="small" :loading="uploadLoading">
                    <el-icon><Picture /></el-icon>
                    上传本地图片
                  </el-button>
                </el-upload>
                <el-button v-else type="text" size="small" disabled>
                  <el-icon><Picture /></el-icon>
                  文件上传已禁用
                </el-button>
                <el-button type="text" size="small" @click="generateCoverUrl">
                  <el-icon><Star /></el-icon>
                  生成随机封面
                </el-button>
                <el-button type="text" size="small" @click="testCoverUrl">
                  <el-icon><Upload /></el-icon>
                  测试封面URL
                </el-button>
              </div>
            </div>
           <!-- 封面预览 -->
           <div class="cover-preview" v-if="form.coverUrl">
             <el-image
               :src="getCoverUrl(form.coverUrl)"
               fit="cover"
               style="width: 100px; height: 100px; border-radius: 8px; border: 1px solid #dcdfe6;"
               @error="handlePreviewError"
             />
           </div>
         </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, Star, Upload, Picture } from '@element-plus/icons-vue'
import { albumApi } from '@/api/album'
import { checkImageUrl, getProxyImageUrl } from '@/api/auth'
import { uploadCover, checkImageExists } from '@/api/upload'
import { getConfigStatus } from '@/api/system'
import { convertToFullUrl, processImageUrl } from '@/utils/urlUtils'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const selectedIds = ref([])
const tableData = ref([])
const uploadLoading = ref(false)
const uploadEnabled = ref(true) // 文件上传是否启用

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const form = reactive({
  id: null,
  name: '',
  description: '',
  coverUrl: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入相册名称', trigger: 'blur' },
    { min: 1, max: 50, message: '相册名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '描述长度不能超过 500 个字符', trigger: 'blur' }
  ]
}

const formRef = ref()
const uploadRef = ref()

// 检查配置状态
const checkConfigStatus = async () => {
  try {
    const response = await getConfigStatus()
    if (response.code === 200) {
      uploadEnabled.value = response.data.uploadEnabled
      if (!uploadEnabled.value) {
        console.log('文件上传功能已被禁用')
      }
    }
  } catch (error) {
    console.error('获取配置状态失败:', error)
  }
}

// 获取相册列表
const getAlbumList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      name: searchForm.name || undefined
    }
    const response = await albumApi.getAlbumList(params)
    if (response.code === 200) {
      tableData.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取相册列表失败')
    }
  } catch (error) {
    console.error('获取相册列表失败:', error)
    ElMessage.error('获取相册列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getAlbumList()
}

// 重置搜索
const handleReset = () => {
  searchForm.name = ''
  pagination.current = 1
  getAlbumList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  getAlbumList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  getAlbumList()
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增相册
const handleAdd = () => {
  dialogTitle.value = '新增相册'
  dialogVisible.value = true
  form.id = null
  form.name = ''
  form.description = ''
  form.coverUrl = ''
}

// 编辑相册
const handleEdit = (row) => {
  dialogTitle.value = '编辑相册'
  dialogVisible.value = true
  form.id = row.id
  form.name = row.name
  form.description = row.description
  form.coverUrl = row.coverUrl
}

// 删除相册
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除相册"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await albumApi.deleteAlbum(row.id)
    if (response.code === 200) {
      ElMessage.success('删除相册成功')
      getAlbumList()
    } else {
      ElMessage.error(response.message || '删除相册失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除相册失败:', error)
      ElMessage.error('删除相册失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的相册')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个相册吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await albumApi.batchDeleteAlbums(selectedIds.value)
    if (response.code === 200) {
      ElMessage.success('批量删除相册成功')
      selectedIds.value = []
      getAlbumList()
    } else {
      ElMessage.error(response.message || '批量删除相册失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除相册失败:', error)
      ElMessage.error('批量删除相册失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    let response
    if (form.id) {
      response = await albumApi.updateAlbum(form)
    } else {
      response = await albumApi.createAlbum(form)
    }
    
    if (response.code === 200) {
      ElMessage.success(form.id ? '更新相册成功' : '创建相册成功')
      dialogVisible.value = false
      getAlbumList()
    } else {
      ElMessage.error(response.message || (form.id ? '更新相册失败' : '创建相册失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交表单失败')
  } finally {
    submitLoading.value = false
  }
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 生成随机封面URL
const generateCoverUrl = () => {
  const colors = ['4f46e5', '10b981', 'f59e0b', '06b6d4', 'ef4444', '8b5cf6', '059669', 'dc2626', '7c3aed', '6b7280']
  const randomColor = colors[Math.floor(Math.random() * colors.length)]
  const randomSeed = Math.random().toString(36).substring(7)
  form.coverUrl = `https://api.dicebear.com/7.x/shapes/svg?seed=${randomSeed}&backgroundColor=${randomColor}&shape1Color=ffffff&shape2Color=818cf8`
}

// 测试封面URL
const testCoverUrl = async () => {
  if (!form.coverUrl) {
    ElMessage.warning('请先输入封面URL')
    return
  }
  
  try {
    const response = await checkImageUrl(form.coverUrl)
    if (response.code === 200) {
      ElMessage.success('封面URL测试成功')
    } else {
      ElMessage.error('封面URL测试失败：' + response.message)
    }
  } catch (error) {
    console.error('测试封面URL失败:', error)
    ElMessage.error('测试封面URL失败')
  }
}

// 获取封面URL（支持代理和本地文件）
const getCoverUrl = (url) => {
  return processImageUrl(url)
}

// 处理图片加载错误
const handleImageError = (e) => {
  console.error('封面图片加载失败:', e)
  ElMessage.warning('封面图片加载失败，请检查URL是否正确')
}

// 处理预览图片加载错误
const handlePreviewError = (e) => {
  console.error('预览图片加载失败:', e)
  ElMessage.warning('预览图片加载失败，请检查URL是否正确')
}

// 文件上传前的验证
const beforeUpload = (file) => {
  // 检查文件上传是否启用
  if (!uploadEnabled.value) {
    ElMessage.error('文件上传功能已被管理员禁用')
    return false
  }
  
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  
  // 检查文件大小（5MB）
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片文件大小不能超过5MB')
    return false
  }
  
  return true
}

// 处理文件上传
const handleUpload = async (options) => {
  const { file } = options
  
  try {
    uploadLoading.value = true
    
    const response = await uploadCover(file)
    
    if (response.code === 200) {
      // 根据是否为新文件显示不同的提示
      if (response.data.isNewFile) {
        ElMessage.success('图片上传成功')
      } else {
        ElMessage.success('图片已存在，直接使用现有文件')
      }
      
      // 将上传后的图片URL设置到表单中（转换为完整URL）
      form.coverUrl = convertToFullUrl(response.data.fileUrl)
      
      console.log('文件信息:', {
        fileName: response.data.fileName,
        fileHash: response.data.fileHash,
        isNewFile: response.data.isNewFile,
        fileUrl: response.data.fileUrl
      })
    } else if (response.code === 403) {
      // 文件上传功能被禁用
      ElMessage.error('文件上传功能已被管理员禁用，请联系管理员')
    } else {
      ElMessage.error(response.message || '图片上传失败')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 页面加载时执行
onMounted(() => {
  checkConfigStatus()
  getAlbumList()
})
</script>

<style lang="scss" scoped>
.page-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.card-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    color: #303133;
  }
  
  .search-container {
    margin-bottom: 20px;
    
    .search-form {
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }
  
  .action-container {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .form-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #909399;
  }
  
  .upload-actions {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
  }
  
  .upload-btn {
    display: inline-block;
  }
  
  .cover-preview {
    margin-top: 12px;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;
  }
}
</style>
